<template>
  <div class="article-edit">
    <el-form :model="articleModel" label-position="left" label-width="120px">
      <el-form-item label="文章标题">
        <el-input v-model="articleModel.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类">
        <el-select v-model="articleModel.type">
          <el-option label="公告" :value="'notice'"></el-option>
          <el-option label="常见问题" :value="'question'"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="articleModel.sort"></el-input-number>
      </el-form-item>
      <el-form-item label="文章内容">
        <h-editor
          v-if="showEditor"
          @change="onContentChange"
          :initContent="articleModel.content"
        ></h-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="success" style="width: 250px;" @click="onSave"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import HEditor from "@/components/HEditor";
import {
  addArticle,
  getArticleDetail,
  updateArticle
} from "@/api/admin-api/ArticleApi";

export default {
  name: "ArticleEdit",
  components: {
    HEditor
  },
  data() {
    return {
      showEditor: false,
      articleModel: {
        id: "",
        sort: 1,
        type: "question",
        content: "",
        title: ""
      }
    };
  },
  methods: {
    onSave() {
      if (this.articleModel.id) {
        //更新
        this.$loading();
        updateArticle(this.articleModel).then(() => {
          this.$message.success("操作成功");
          this.$loading().close();
          setTimeout(() => {
            this.$router.go(0);
          }, 500);
        });
      } else {
        //保存
        this.$loading();
        addArticle(this.articleModel).then(() => {
          this.$message.success("保存成功");
          this.$loading().close();
          this.$router.back();
        });
      }
    },
    onContentChange(value) {
      console.log(value);
      this.articleModel.content = value;
    },
    loadArticleDetail() {
      getArticleDetail(this.articleModel.id).then(data => {
        this.articleModel = data;
        this.showEditor = true;
      });
    }
  },
  mounted() {
    this.articleModel.id = this.$route.query.id;
    if (this.articleModel.id) {
      // 编辑模式
      this.loadArticleDetail();
    } else {
      this.showEditor = true;
    }
  }
};
</script>

<style scoped>
.article-edit {
  padding: 20px;
  background-color: #ffffff;
  margin: 15px;
  border-radius: 8px;
  box-shadow: 4px 4px 8px 0px #b2b2b2;
}
.article-edit >>> .w-e-text-container {
  height: 600px !important; /*!important是重点，因为原div是行内样式设置的高度300px*/
}
</style>
